<script setup>
// 引入ref
import { ref } from "vue"
// 引入computed
import { computed } from "vue"

// 声明响应式变量,自动解包
const books = ref([
  {
    id: 1,
    name: "《算法导论》",
    date: "2006-9",
    price: 85.0,
    count: 1,
  },
  {
    id: 2,
    name: "《UNIX编程艺术》",
    date: "2006-2",
    price: 59.0,
    count: 1,
  },
  {
    id: 3,
    name: "《编程珠玑》",
    date: "2008-10",
    price: 39.0,
    count: 1,
  },
  {
    id: 4,
    name: "《代码大全》",
    date: "2006-3",
    price: 128.0,
    count: 1,
  },
])

const handleReduce = (item) => {
  if (item.count === 1) return
  item.count--
}

const handleAdd = (item) => {
  item.count++
}

const handleRemove = (index) => {
  books.value.splice(index, 1)
}

// 计算属性

const totalPrice = computed(() => {
  return (
    "$" +
    books.value.reduce((total, book) => total + book.price * book.count, 0)
  )
})
</script>

<!-- 表格内容 -->
<template>
  <div>
    <table>
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th></th>
          <th>书籍名称</th>
          <th>出版日期</th>
          <th>价格</th>
          <th>购物数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in books" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.date }}</td>
          <td>${{ item.price }}</td>
          <td>
            <button @click="handleReduce(item)">-</button>
            {{ item.count }}
            <button @click="handleAdd(item)">+</button>
          </td>
          <td>
            <button @click="handleRemove(item.index)">移除</button>
          </td>
        </tr>
        <tr v-if="books.length === 0" style="height: 50px">
          购物车已经空空如也
        </tr>
        <tr>
          <td colspan="6" style="text-align: right">总价格:{{ totalPrice }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style scoped>
table,
td,
tr,
th {
  border: 2px solid rgb(242, 242, 242);
  border-collapse: collapse;
  padding: 10px;
}
th {
  background-color: rgb(247, 247, 247);
}
caption,
th {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
